package com.git.resolver;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.git.annotation.GetUser;
import com.git.constants.Constans;
import com.git.domain.User;
import com.git.service.UserService;

public class GetUserResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private UserService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //判断参数上是不是User对象并且@GetUserResolver
        if (parameter.getParameterType().isAssignableFrom(User.class) &&
                parameter.hasParameterAnnotation(GetUser.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    	//取出存入的id
    	String id = (String) webRequest.getAttribute(Constans.REQUEST_ID, RequestAttributes.SCOPE_REQUEST);
    	
    	if (StringUtils.isNotBlank(id)) {
			return this.userService.getUserById(id);
		}
        return null;
    }
}